<template>
  <!-- 发起审核: 无在处理的流程或已经驳回的流程 展示空白表单 重新发起审核 -->
  <sticky-operation-dialog v-if="shouldShowInitiateApproval" v-model:visible="visible">
    <!-- 骨架屏 -->
    <t-skeleton :loading="loadingSkeleton" animation="gradient" style="min-width: 300px">
      <!-- 关闭按钮 -->
      <div style="text-align: end">
        <t-icon name="close" color="#666666" size="20px" @click="visible = false" />
      </div>
      <t-space align="center" size="50px">
        <!-- 表单 -->
        <t-form ref="formRef" :data="formData" style="width: 360px">
          <t-form-item label="审批类型" name="type">
            {{ dictionaryStore.analysis('order_approval_type', props.approveType) }}
          </t-form-item>
          <t-form-item
            v-if="['2'].includes(props.approveType)"
            label="申请日期"
            name="extensionTime"
            :rules="[{ required: true, message: '请选择申请日期' }]"
          >
            <div v-if="isInApprove">{{ approveData.extensionTime }}</div>
            <t-date-picker
              v-else
              allow-input
              v-model:value="formData.extensionTime"
              clearable
              value-type="time-stamp"
              placeholder="请选择申请日期"
              @change="
                (value) => {
                  if (value) {
                    value = dayjs(value).format('YYYY-MM-DD 23:59:59');

                  }
                  formData.extensionTime = value ? value : undefined;
                }
              "
              style="width: 100%"
            />
          </t-form-item>
          <t-form-item
            v-if="['2', '4'].includes(props.approveType)"
            label="申请备注"
            name="extensionRemark"
            :rules="[{ required: true, message: '请输入申请备注' }]"
          >
            <t-textarea v-model:value="formData.extensionRemark" placeholder="请输入申请备注" />
          </t-form-item>
          <t-form-item>
            <t-button :loading="loadingSubmit" @click="handleSave">提交审批</t-button>
          </t-form-item>
        </t-form>
      </t-space>
    </t-skeleton>
  </sticky-operation-dialog>

  <!-- 发起人-审批记录-处理中 -->
  <sticky-operation-dialog :is-multiple="props.isMultiple" :style="props.style" v-if="isInApproveOrder && processInstanceTaskList.length&& isInitialUser&&!isAssigneeUser"  v-model:visible="visible">
    <!-- 骨架屏 -->
    <t-skeleton :loading="loadingSkeleton" animation="gradient" style="min-width: 300px">
      <!-- 关闭按钮 -->
      <div style="text-align: end">
        <t-icon name="close" color="#666666" size="20px" @click="visible = false" />
      </div>
      <t-space align="center" size="50px">
        <!-- 流程实例过程-发起人 -->
        <t-timeline v-if="isInitialUser"  mode="same">
          <t-timeline-item v-for="(_,index) in processInstanceTaskList" :key="_.id">
            <div class="timeline-item-content">
              <div class="item" v-if="index==0">
                <div class="center">{{startData.oaName}}</div>
                <!-- <div class="content">：{{ _.name }}</div> -->
              </div>
              
              <div class="item">
                <div class="title">任务名称</div>
                <div class="content">：{{ _.name }}</div>
              </div>
              <div class="item">
                <div class="title">审批状态</div>
                <div class="content">：{{ dictionaryStore.analysis('bpm_task_status', _.status) }}</div>
              </div>
              <div class="item">
                <div class="title">审批人</div>
                <div class="content">：{{ _.assigneeUser?.deptName }} - {{ _.assigneeUser?.nickname }}</div>
              </div>
              <div class="item">
                <div class="title">审批备注</div>
                <div class="content">：{{ _.reason }}</div>
              </div>
            </div>
            <template #label>
              <div class="timeline-item-label">
                <div class="item">
                  <div class="title">创建时间</div>
                  <div class="content">：{{ dayjs(_.createTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
                </div>
                <div v-if="_.endTime" class="item">
                  <div class="title">审批时间</div>
                  <div class="content">：{{ dayjs(_.endTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
                </div>
                <div v-if="_.durationInMillis" class="item">
                  <div class="title">耗时</div>
                  <div class="content">：{{ (_.durationInMillis / 1000 / 60).toFixed(1) }}分钟</div>
                </div>
              </div>
            </template>
          </t-timeline-item>
        </t-timeline>
        
      </t-space>
    </t-skeleton>
  </sticky-operation-dialog>

 
  
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { Form, MessagePlugin } from 'tdesign-vue-next';
import { computed, ref, useTemplateRef } from 'vue';

import {
  applyAbandonedOrder,
  getProcessInstance,
  getProcessInstanceIdByOrderIdAndType,
  getProcessInstanceTaskList,
  transformDesignExtension,
} from '@/api/approve/approve';
import StickyOperationDialog from '@/components/sticky-operation-dialog/index.vue';
import { useDictionaryStore, useUserStore } from '@/store';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 用户仓库
const userStore = useUserStore();
// props
const props = defineProps({
  // 订单id
  orderId: {
    type: Number,
    required: true,
  },
  // 审批类型
  approveType: {
    type: String,
    required: true,
  },
  isMultiple: {
    type: Boolean,
    default: false
  },
  style: {
    type: Object,
    default: {}
  }
});
// 显示
const visible = ref(false);
// 表单ref
const formRef = useTemplateRef<typeof Form>('formRef');
// 表单数据
const formData = ref<Record<string, any>>({});
// 审批数据
const approveData = ref<Record<string, any>>({});
// 发起流程-结束流程
const startData = ref<Record<string, any>>({})
// 是否正在审批--审批人
const isInApprove = computed(() => {
  return approveData.value.status === 1;
});
// 是否正在审批--订单
const isInApproveOrder = computed(() => {
  return approveData.value.designStatus === 1;
});
// 是发起审批用户
const isInitialUser = computed(() => {
  return startData.value.userId === userStore.userInfo.id;
});
// 是否审批用户
const isAssigneeUser = computed(() => {
  console.log('isAssigneeUser', approveData.value.assigneeUserId, userStore.userInfo.id);
  return approveData.value.assigneeUserId === userStore.userInfo.id;
});
// 是否展示发起审核表单
const shouldShowInitiateApproval = computed(() => {
  // 条件 1：没有审批流程或 designStatus 为 3（驳回）
  const isCondition1True = !(isInApproveOrder.value && processInstanceTaskList.value.length) || approveData.value.designStatus === 3;

  // 条件 2：approveType 为 2 或 4
  const isCondition2True = ['2', '4'].includes(props.approveType);

  // 同时满足条件 1 和条件 2
  return isCondition1True && isCondition2True;
});
// 处理获取流程实例
const handleGetProcessInstance = (id: string) => {
  const params = {
    id,
  };
  return getProcessInstance(params)
    .then((data) => {
      if(data) {
        approveData.value.designStatus = data.status;
      Object.keys(data.formVariables).forEach((key) => {
        approveData.value[key] = data.formVariables[key];
      });
      startData.value.endTime = data.endTime
      startData.value.startTime = data.startTime
      startData.value.processName = data.name
      startData.value.userName = data.startUser.nickname
      startData.value.userId = data.startUser.id
      startData.value.oaName = data.name
      }

      
    })
    .catch((message) => {
      console.log(message);
      MessagePlugin.error(message);
    });
};
// 流程实例任务列表
const processInstanceTaskList = ref([]);
// 处理获取流程实例任务列表
const handleGetProcessInstanceTaskList = (processInstanceId: string) => {
  const params = {
    processInstanceId,
  };
  return getProcessInstanceTaskList(params)
    .then((data) => {
      if(data&&data.length>0) {
        processInstanceTaskList.value = data;
      data.forEach((item:any) => {
        if (item.assigneeUser?.id === userStore.userInfo.id) {
          approveData.value.taskId = item.id;
          approveData.value.assigneeUserId = item.assigneeUser.id;
          approveData.value.status = item.status;
        }
      });
      startData.value.status = data[0].status
      }

      // approveData.value.taskId = data[0].id;
      // approveData.value.assigneeUserId = data[0].assigneeUser.id;
    })
    .catch((message) => {
      console.log(message);
      
      MessagePlugin.error(message);
    });
};
// 加载骨架屏
const loadingSkeleton = ref(false);
// 处理获取审批数据
const handleGetApproveData = async () => {
  formData.value = {};
  loadingSkeleton.value = true;
  const params = {
    orderId: props.orderId,
    type: props.approveType,
  };
  try {
    const data = await getProcessInstanceIdByOrderIdAndType(params);
    const processInstanceId = data[0];
    console.log(processInstanceId,'processInstanceIdinit');
    
    if (processInstanceId) {
      console.log(1122222,processInstanceId);
      
      visible.value = true
      await handleGetProcessInstance(processInstanceId);
      await handleGetProcessInstanceTaskList(processInstanceId);
    }
  } catch (error) {    
    MessagePlugin.error(error);
  } finally {
    loadingSkeleton.value = false;
  }
};
// 加载提交
const loadingSubmit = ref(false);
// 提交api
const submitApi = {
  2: transformDesignExtension, // 转设计延期
  4: applyAbandonedOrder, // 申请废单
}[props.approveType];
// 处理提交
const handleSave = async () => {
  const validateResult = await formRef.value.validate();
  if (validateResult !== true) return;
  const params = {
    orderId: props.orderId,
    ...formData.value,
  };
  loadingSubmit.value = true;
  submitApi(params)
    .then(() => {
      MessagePlugin.success('提交成功');
      // handleGetApproveData();
      visible.value = false;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      loadingSubmit.value = false;
    });
};
// 打开
const open =async () => {
 
  // if(shouldShowInitiateApproval.value || (isInApproveOrder.value && processInstanceTaskList.value.length&& isInitialUser.value)) {
    await handleGetApproveData();
  // };
};
// 关闭
const close = () => {
  visible.value = false;
};

defineExpose({
  open,
  close,
  visible,
});
</script>

<style lang="less" scoped>
.timeline-item-content {
  .item {
    font-size: var(--td-font-body-medium);
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .center {
      font-weight:bold;
      margin: 0 auto;
    }

    .title {
      width: 64px;
      text-align: justify;
      text-align-last: justify;
    }
  }
}

.timeline-item-label {
  margin-top: 6px;

  .item {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .title {
      width: 56px;
      text-align: justify;
      text-align-last: justify;
    }
    .color-gray {
      color: gray;
    }
  }
  
}
</style>
